<script setup>
/**
 * @description: 抽屉组件-文字标题
 * @param {*}
 * @return {*}
 */
import {
  ref,
  reactive,
  nextTick,
  watch,
  onMounted,
  computed,
  createVNode,
} from "vue";

// 处理配置应用到全部字幕组
import {
  applyallTitle,
  textImportToTitle,
  // 视频截取首帧画面
  captureFirstFrame,
} from "@/common/utils/richTextProcessing.js";

// 素材库组件
import ChooseMaterial from "@/views/shotstack/EditingCenter/modules/bottomSet/components/chooseMaterial.vue";
import newChooseMaterial from "@/views/shotstack/EditingCenter/modules/bottomSet/components/newChooseMaterial.vue";

// 花字组件
import FancyFont from "./FancyFont.vue";
const fancyFont = ref(null);

// 风险词检测组件
import Risk_test from "./Component/Risk_test.vue";
const Risk_testRef = ref(null);

// 字幕特效设置
import SubtitleSpeciallyGoodEffectDialog from '@/views/shotstack/components/SubtitleSpeciallyGoodEffectDialog/index.vue'
const SubtitleSpeciallyGoodEffectDialogRef = ref()

// 字幕特效 tips 文案获取
import {getEffectsTips} from '@/common/utils/atherUtils.js'

import _ from "lodash";
// 获取随机id
import { nanoid } from "nanoid";

// 枚举数据和工具
import {
  calculateDraggableArea,
  baseText_config,
  hexToRgba,
  resetXY,
  // 获取当前元素的宽度辅助函数
  measureTextWithSpan,
} from "../../utools/index.js";
// icon
import {
  CloseOutlined,
  CopyOutlined,
  ExclamationCircleOutlined,
  InfoCircleOutlined,
} from "@ant-design/icons-vue";
// 轻提示
import { message, Modal } from "ant-design-vue";
// 自定义工具
import { changeFocus } from "../../utools/index.js";
//
import request from "@/common/utils/request";

import utils from "@/common/utils/utils.js";

// 仓库
// import store from "@/store";

// 手机组件
import { DraggableContainer } from "vue3-draggable-resizable";

import Vue3DraggableResizable from "vue3-draggable-resizable";
//default styles
import "vue3-draggable-resizable/dist/Vue3DraggableResizable.css";
// 仓库
import { useStore } from "vuex";
import RiskWordDetection from "../components/riskWordDetecDrawer.vue";
// 文案库组件
import CopyLibraryModal from "@/components/AddTextModal/CopyLibraryModal.vue";

import dayjs from "dayjs";

const store = useStore();
let state = ref([]);
// 仓库中的混剪数据
const VideoMashup = computed(() => {
  return store.state.videoMixCut.VideoMashup;
});

const props = defineProps({
  title: {
    type: String,
    default: "添加文字",
  },
});

// 背景设置的参数
const bgc = computed(() => {
  const data = store.state.videoMixCut.VideoMashup.background
  if (data?.type == 1) {
    return {
      'background': data.rgba
    }
  } else if (data?.type == 2 || data?.type == 3) {
    let url = data.material_urls[0].url
    return {
      'background': `url(${url})`,
      'background-position': 'center',
      'background-size': 'cover'
    }
  } else {
    return {
      'background': '#707070'
    }
  }
});

// 当前预览的下标
const currentDrawerIndex = ref(0);

// 素材库开关
const materiallibraryShow = ref(false);

let copyLibraryModal = ref(null); //文案库导入组件实例
const openCopyLibraryModal = () => {
  copyLibraryModal.value && copyLibraryModal.value.showModal();
};
// 文案库选择文本回调
const closeChooseMaterial = (data) => {
  textImportToTitle({
    data,
    state,
    activeTextarea,
    copyLibraryModal,
    currentDrawerIndex,
    type: "item",
  });
};

// 文本框自动适应高度
const autoResize = (event) => {
  const textarea = event.target;
  // 重置textarea的高度（这步很重要，能够在删除内容时减小textarea的高度）
  textarea.style.height = "auto";
  // 让textarea的高度等于它的滚动高度，这样就能够完全容纳它的内容
  textarea.style.height = `${textarea.scrollHeight}px`;
};
// 高亮的项
const activeTextarea = ref(0);

// 修改当前高亮项的高度
const changeHeight = () => {
  nextTick(() => {
    changeFocus(`[data-textareaId="${activeTextarea.value}"]`, false);
    const textareaDom = document.querySelector(
      `[data-textareaId="${activeTextarea.value}"]`
    );
    const findTarget = state.value[currentDrawerIndex.value].text_config.find(
      (ele) => ele.id == activeTextarea.value
    );
    textareaDom && (textareaDom.style.height = "auto");
    nextTick(() => {
      if (!!findTarget && findTarget.text == "") {
        textareaDom && (textareaDom.style.height = `${26}px`);
      } else {
        textareaDom &&
          (textareaDom.style.height = `${textareaDom.scrollHeight}px`);
      }
    });

    //改变当前侦听的聚焦项
    unobserveAllSpans();
    observeActiveSpan();
  });
};

// 实时变更聚焦点
watch(
  () => activeTextarea.value,
  (nv, ov) => {
    changeHeight();
  },
  {}
);

// 实时获取高亮的项的index
const activeIndex = computed(() => {
  // 当前选中的那一项
  const tergetArr = state.value[currentDrawerIndex.value].text_config;

  return tergetArr.findIndex((ele) => ele.id === activeTextarea.value);
});

// 当前正在编辑的项
const current_editItem = computed(() => {
  console.log(state.value[currentDrawerIndex.value], "当期那编辑的标题项");
  return state.value[currentDrawerIndex.value];
});

// 获取风险词文字数组
const text_arr = computed(() => {
  if (state.value[currentDrawerIndex.value]) {
    const arr = state.value[currentDrawerIndex.value]?.text_config.map(
      (ele) => ele.text
    );
    return {
      arr,
      text: arr.join(""),
    };
  } else {
    return {
      arr: [],
      text: "",
    };
  }
});

// 删除条件为, 不能删除第一个项
const textareaKeydown = (event, index) => {
  // 获取当前显示的span的宽度
  // 编辑的这一组
  const tergetArr = state.value[currentDrawerIndex.value].text_config;
  // 编辑的这一项
  const targetItem = tergetArr[index];
  if (event.key == "Backspace" && targetItem) {
    if (tergetArr.length <= 1 && targetItem.text.length <= 0) {
      event.preventDefault();
      message.warning("至少需要一个标题!");
      return;
    } else if (tergetArr[index].text.length <= 0) {
      event.preventDefault();
      if (index < tergetArr.length - 1) {
        activeTextarea.value = tergetArr[index + 1].id;
      } else {
        activeTextarea.value = tergetArr[index - 1].id;
      }
      tergetArr.splice(index, 1);
    }
  } else if (event.shiftKey && event.key == "Enter") {
    return;
  } else if (event.key == "Enter") {
    event.preventDefault();
    addTextareaItem(index, "add");
  }
};

// 点击项获取焦点
const focusItem = (id) => {
  activeTextarea.value = id;
};

// 字体组件的更新和修改
const updateState = (data) => {
  console.log(data, "触发子组件通知");
  // 确保目标对象存在，否则使用一个空对象作为默认值
  const target =
    state.value?.[currentDrawerIndex.value]?.text_config?.[activeIndex.value] ||
    {};
  console.log(target, "目标数据");
  Object.assign(target, { ...data });
};

// 添加标题
const addTextareaItem = (index, type) => {
  const tergetArr = state.value[currentDrawerIndex.value].text_config;
  if (tergetArr.length >= 5) {
    message.warning("最多只能添加5个标题!");
    return;
  }
  const timeId = nanoid();
  if (type === "add") {
    const baseText_config_data = baseText_config();
    baseText_config_data.id = timeId;
    tergetArr.splice(index + 1, 0, baseText_config_data);
  } else if (type === "copy") {
    tergetArr.splice(index + 1, 0, {
      ...tergetArr[index],
      id: timeId,
    });
  }
  // return;
  activeTextarea.value = timeId;
};

const title_top = ref("");

const resizeObserver = ref(null);

// 开始侦听所有的span 元素
const observeActiveSpan = () => {
  // debugger
  nextTick(() => {
    const activeElement = document.getElementById(
      "cover_" + activeTextarea.value
    );
    if (activeElement) {
      resizeObserver.value.observe(activeElement);
    } else {
      console.warn("找不到元素", "cover_" + activeTextarea.value);
    }
  });
};

// 取消侦听span
const unobserveAllSpans = () => {
  const span = document.getElementById("cover_" + activeTextarea.value);
  resizeObserver.value.unobserve(span);
};

// 手机中 span 的宽度
const spanWidth = ref("");

// 控制抽屉的显示与隐藏
const visible = ref(false);
const openDrawer = async (index) => {
  // 侦听span的宽度变化
  resizeObserver.value = new ResizeObserver((entries) => {
    for (let entry of entries) {
      // console.log(entry, '元素变化', activeTextarea.value);
      const computedStyle = getComputedStyle(entry.target);
      // 计算包含 padding 的宽度
      const paddingLeft = parseFloat(computedStyle.paddingLeft);
      const paddingRight = parseFloat(computedStyle.paddingRight);
      const totalWidth = entry.contentRect.width + paddingLeft + paddingRight;
      spanWidth.value = totalWidth;
      // spanWidth.value = entry.contentRect.width;
      const target =
        state.value[currentDrawerIndex.value].text_config[activeIndex.value];
      if (spanWidth.value && target) {
        console.log(spanWidth.value, "span 的宽度");
        const x = target.showX - spanWidth.value / 2
        const rightX = target.showX + spanWidth.value / 2
        target.x = x < 0 ? 0 : x
        target.rightX = rightX
      }

    }
  });

  currentDrawerIndex.value = index.index;
  useBgc();
  // 克隆数据, 用于修改 最后保存
  state.value = JSON.parse(JSON.stringify(VideoMashup.value.resource_data));

  // 初始赋值id
  activeTextarea.value =
    state.value[currentDrawerIndex.value].text_config[0].id;

  title_top.value =
    VideoMashup.value.resource_data[currentDrawerIndex.value].name;

  // 存储当前的分辨率
  distinguishability.value.width = VideoMashup.value.width;
  distinguishability.value.height = VideoMashup.value.height;

  // 回显随机花字
  flower_random_config.value = JSON.parse(JSON.stringify(state.value[currentDrawerIndex.value].flower_random_config))


  visible.value = true;

  nextTick(() => {
    // 侦听span元素的宽度
    observeActiveSpan();
    changeHeight();
  });

  getFontClass();
  setTimeout(() => {
    phoneVisible.value = true;
  }, 550);
};

const background = ref({
  type: "color",
  url: "transparent",
});

// 使用的背景
const useBgc = async () => {
  // 判断使用的背景
  const material =
    VideoMashup.value.resource_data?.[currentDrawerIndex.value]
      .material_list?.[0];

  if (material?.scene_type == "video") {
    const url = await captureFirstFrame(material.material_url);
    
    if (url) {
      background.value = { url, type: "img" };
    } else {
      background.value = "transparent";
      background.value = { url: "transparent", type: "color" };
    }
  } else if (material?.scene_type == "image") {
    const url = material.material_url;
    url
      ? (background.value = { url, type: "img" })
      : (background.value = { url: "transparent", type: "color" });
  } else {
    background.value = { url: "transparent", type: "color" };
  }
};

const closeDrawer = () => {
  // 取消侦听span的宽度
  unobserveAllSpans();
  visible.value = false;
  phoneVisible.value = false;
};
// 每一项的持续时长
const text_duration = computed({
  get() {
    const text_duration =
      state.value[currentDrawerIndex.value].text_config[activeIndex.value]
        ?.text_duration;
    return text_duration ? text_duration / 1000 : "";
  },
  set(val) {
    state.value[currentDrawerIndex.value].text_config[
      activeIndex.value
    ].text_duration = val * 1000;
  },
});

// 每一项的开始时间

const text_startTime = computed({
  get() {
    return (
      state.value[currentDrawerIndex.value].text_config[activeIndex.value]
        ?.start_time / 1000
    );
  },
  set(val) {
    state.value[currentDrawerIndex.value].text_config[
      activeIndex.value
    ].start_time = val * 1000;
  },
});

/**
 * 手机相关
 */

const radioType = computed(() => store.getters.clipJSON?.aspect_ratio);

// 控制手机显示隐藏
const phoneVisible = ref(false);
// 加载效果
const loading = ref(false);

// const coverList = ref([]);

// 获取渲染的每一项数据
const getPosition = computed(() => {
  const targetData = JSON.parse(
    JSON.stringify(state.value[currentDrawerIndex.value].text_config)
  );
  targetData.forEach((ele) => {
    const dom = document.getElementById("cover_" + ele.id);
    nextTick(() => {
      // ele.height = dom?.offsetHeight || 0;
      (ele.width = dom?.offsetWidth || 0),
        (ele.height = dom?.offsetHeight || 0),
        (ele.active = false);
    });
  });
  return targetData;
});

// 分辨率
const distinguishability = ref({
  width: "",
  height: "",
});
// 获取当前选中的弹幕
const resizableStyle = computed(() => {
  const sizeData = calculateDraggableArea(
    +distinguishability.value.width,
    +distinguishability.value.height
  );
  return {
    // backgroundImage: `url(https://ui.biaodianyun.com/dy-saas/admin-pc/assets/bg_cover-d353011d.png), url(${coverForm.value.poster_url}), url(https://hf.pigcms.com/static/wxapp/images/phone_black_back.png)`,
    // backgroundSize: "100% auto",
    // backgroundPosition: "center center",
    // backgroundRepeat: "no-repeat",
    // background: "#707070",
    // background: "#ffffff",
    width: sizeData.draggableWidth + "px",
    height: sizeData.draggableHeight + "px",
    transition: "all 0.3s",
    'z-index': 1,

  };
});

// 素材背景
const parentBgc = computed(() => {
  let returnVal =
    background.value.type == "color"
      ? {
        background: background.value.url,
      }
      : {
        background: `url(${background.value.url})`,
        'background-repeat': 'no-repeat',
        'background-size': 'contain',
        "backgroundPosition": "center",
      };

  return returnVal
})


// 字体列表
const typefaceOptions = ref([]);
// 文字外边框的宽高

// 当前使用的字体样式
// 计算字体样式
const coverStyle = computed(() => {
  return function (item, index, id) {
    // 计算字体的显示比例
    const size = item.font_size;
    const width = VideoMashup.value.showWidth;
    const height = VideoMashup.value.showHeight;
    // 获取当前缩放的比例
    const { scaleWidth } = resetXY(height, width);
    // const font_size = (size / scaleWidth) * 1.058
    const font_size = size / scaleWidth
    nextTick(() => {
      let domObj = document.getElementById("cover_" + id);
      // 复制一个元素, 计算宽度
      const width = measureTextWithSpan(domObj, domObj.textContent).width;
      item.width = width;
      item.height = domObj?.offsetHeight;
    });

    let flower_style;
    // 获取花字的对应样式
    const shadow = () => {
      let { borderw, bordercolor } = item?.preset_styles_config;
      borderw = borderw / 3;
      if (borderw && bordercolor) {
        const shadows = [];
        for (let x = -borderw; x <= borderw; x++) {
          for (let y = -borderw; y <= borderw; y++) {
            if (x !== 0 || y !== 0) {
              shadows.push(`${x}px ${y}px 0 ${bordercolor}`);
            }
          }
        }
        return shadows.join(",");
      } else {
        return "";
      }
    };
    flower_style = {
      // 字体颜色
      color: item?.preset_styles_config.fontcolor || item.color,
      // 转换背景色和透明度
      "background-color": hexToRgba(
        item?.preset_styles_config.boxcolor,
        item?.preset_styles_config.box_color_alpha
      ),
      // 整体透明度
      // 边框的粗细
      padding: `${item?.preset_styles_config?.boxborderw
        ? item?.preset_styles_config?.boxborderw / 4
        : 0
        }px`,
      "border-radius": item?.preset_styles_config.boxradius / 3 + "px",
      "text-shadow": shadow(),
    };
    const returnData = {
      cursor: "grab",
      "font-family": item.font_family,
      "font-size": font_size + "px",
      color: item.color,
      "background-color": item.bg_color,
      "font-weight": item.bold == 1 ? "bold" : "normal",
      "font-style": item.italic == 1 ? "italic" : "normal",
      textAlign:
        item.alignment == "left"
          ? "left"
          : item.alignment == "right"
            ? "right"
            : "center",
    };
    if (!!flower_style) {
      return {
        ...returnData,
        ...flower_style,
      };
    } else {
      return returnData;
    }
  };
});

const coverForm = ref({
  cover_duration: 0.05,
  poster_url: "",
});

const customFont = (name, url) => {
  const fontFace = new FontFace(name, `url(${url})`);
  fontFace
    .load()
    .then(() => {
      document.fonts.add(fontFace);
      loading.value = false;
    })
    .catch((error) => {
      console.error(error);
      loading.value = false;
    });
};
const Phoneloading = ref(false);
const getFontClass = () => {
  typefaceOptions.value = [];
  request.get("/work_ai", "/user/shotstack/material/fonts/list").then((res) => {
    res.result.map((item) => {
      item.label = item.name;
      item.value = item.material_url;
      typefaceOptions.value.push(item);
    });
    console.log(typefaceOptions.value, "typefaceOptions.value");
    if (!props.coverObj?.list) {
      let material_url = typefaceOptions.value.find(
        (item) => item.name == "站酷快乐体"
      ).material_url;
      coverForm.value.poster_url = "";
      coverForm.value.cover_duration = 0.05;
      Phoneloading.value = true;
      customFont("HappyZcool-2016", material_url);
    }
  });
};

// 拖拽结束回调
const dragEndHandle = (ev, item) => {
  const dom = document.getElementById("cover_" + item.id);
  const width = dom?.offsetWidth;
  // item.x = item.showX - width / 2;
  // item.x = ev.x - width / 2;
  item.x = ev.x;
  item.showX = (ev.x + width / 2) + 1.5;
  item.rightX = ev.x + width
  item.y = ev.y;
  activeTextarea.value = item.id;
  console.log(item.x, "拖拽结束", item.showX);
};
// 切换镜头组
const changePreview = (type) => {
  // 上一个
  if (type == "last") {
    if (currentDrawerIndex.value > 0) {
      currentDrawerIndex.value = currentDrawerIndex.value - 1;
      title_top.value =
        VideoMashup.value.resource_data[currentDrawerIndex.value].name;

      // nextTick(() => {
      //   const target = state.value[currentDrawerIndex.value];
      //   Risk_testRef.value.setRisk_types(target?.risk_data_text_config);
      // });
    }
  } else if (type == "next") {
    // 下一个
    if (currentDrawerIndex.value < state.value.length - 1) {
      currentDrawerIndex.value = currentDrawerIndex.value + 1;
      title_top.value =
        VideoMashup.value.resource_data[currentDrawerIndex.value].name;
      // nextTick(() => {
      //   const target = state.value[currentDrawerIndex.value];
      //   Risk_testRef.value.setRisk_types(target?.risk_data_text_config);
      // });
    }
  }
  state.value[currentDrawerIndex.value].text_config.forEach((ele) => {
    !ele?.id && (ele.id = _.uniqueId());
  });
  activeTextarea.value =
    state.value[currentDrawerIndex.value].text_config[0].id;

  useBgc();
};

const close = () => {
  Modal.confirm({
    title: "温馨提示",
    icon: createVNode(ExclamationCircleOutlined),
    content: "当前未保存，是否退出设置，退出后将不会保存这次编辑",
    cancelText: "取消",
    okText: "确认",
    onOk() {
      closeDrawer();
    },
    onCancel() { },
    class: "test",
  });
};

// 点击确定保存数据
const submitConfirm = () => {
  state.value[currentDrawerIndex.value].flower_random_config = JSON.parse(JSON.stringify(flower_random_config.value))
  store.dispatch("videoMixCut/SetVideoMashupItem", {
    key: "resource_data",
    // 克隆, 防止关闭后导致的侦听 影响提交数据
    value: JSON.parse(JSON.stringify(state.value)),
  });
  // nextTick(() => {
  closeDrawer();
  // });
};

// 配置应用到全部
const applyToAll = () => {
  // 基础数据, 用于替换其他视频组的数据
  Modal.confirm({
    title: "视频设置应用到全部镜头组",
    icon: createVNode(ExclamationCircleOutlined),
    content: "是否视频设置应用到全部镜头组？",
    okText: "确认",
    cancelText: "取消",
    onOk() {
      const data = applyallTitle({
        state,
        currentDrawerIndex,
        activeTextarea,
      });
      // 修改全部的
      store.dispatch("videoMixCut/SetVideoMashupItem", {
        key: "resource_data",
        value: data,
      });
    },
    onCancel() { },
    class: "test",
  });
};

// 是否显示背景图
const showImg = ref(true);

// 修改所有的项的x轴数据, 触发函数

// 风险词检测结束
const testOver = (risk_data) => {
  console.log(risk_data, "风险词检测结束");
  if (risk_data) {
    // const target = state.value[currentDrawerIndex.value].text_config
    const target = state.value[currentDrawerIndex.value];
    // current_tts_data.value.risk_data = risk_data
    target.risk_data_text_config = risk_data;
    // target.risk_data = risk_data
  }
};

// 风险词检测
const riskWordDetection = ref(null);
const riskWordDetnHandle = () => {
  console.log(text_arr.value.arr);
  const isImpty = text_arr?.value?.arr?.some((item) => item.trim().length > 0);
  if (isImpty) {
    riskWordDetection.value &&
      riskWordDetection.value.showDrawer(text_arr?.value.arr, "literalTitle");
  } else {
    message.warning("请输入标题");
  }
};


// 随机花字
const flower_random_config = ref({})

// 更新是否随机参数
const updateIsRandom = (val) => {
  console.log('执行了', val);
  flower_random_config.value.isRandom = val
}

// 更新选择的列表参数
const updateConfig_ids = (list) => {
  flower_random_config.value.flower_config_ids = list
}

// 更新花字tab栏位
const updateFlower_type = (val) => {
  flower_random_config.value.flower_type = val
} 

const clearFlower_config_ids = () => {
  flower_random_config.value.flower_config_ids = []
}
// 更改当前选择的 花字id
const updateFlower_id = (id) => {
  // 确保目标对象存在，否则使用一个空对象作为默认值
  const target = state.value?.[currentDrawerIndex.value]?.text_config?.[activeIndex.value] || null;
  if (!!target) {    
    target.preset_styles_config.id = id;
    target.flower_id = id;
  }
  console.log(state.value,'修改了花字id');
}

// 字幕特效设置
const subtitleSpecialEffects = (i) => {
  const subtitle_effects = i?.subtitle_effects;
  SubtitleSpeciallyGoodEffectDialogRef.value?.open({subtitle_effects})
}

// 数据选择回调
const updateTextEffect_config = (confige) => {
  console.log(confige, '修改后的confige字幕特效');
  const findTarget = state.value[currentDrawerIndex.value].text_config.find(
      (ele) => ele.id == activeTextarea.value
  );
  if (findTarget) {
    findTarget.subtitle_effects = JSON.parse(JSON.stringify(confige))
  }
}



defineExpose({
  openDrawer,
  closeDrawer,
});
</script>

<template>
  <div class="literalTitleDrawer">
    <transition>
      <a-drawer v-model:visible="visible" placement="right" :keyboard="true" width="50%" :closable="false"
        :maskClosable="false" :destroyOnClose="true" :bodyStyle="{
          minWidth: '420px',
          paddingTop: 0,
        }" getContainer=".literalTitleDrawer">
        <slot name="title">
          <div class="title_box">
            <div class="title_top">
              <h1 class="title">添加文字-{{ title_top }}</h1>
              <div class="close" @click="closeDrawer">
                <CloseOutlined />
              </div>
            </div>
            <div class="title_bottom">
              <a-button class="btn_prev" @click="changePreview('last')" style="margin-right: 10px"
                :disabled="currentDrawerIndex == 0">上一个镜头组</a-button>
              <a-button @click="changePreview('next')" class="btn_prev"
                :disabled="currentDrawerIndex == state.length - 1">下一个镜头组</a-button>
            </div>
          </div>
        </slot>

        <div class="content">
          <!-- 添加标题 -->
          <div class="content_item">
            <div class="content_item_title">
              <div class="content_item_title_left">
                <h2>添加标题</h2>
                <span>shift + enter 行内折行</span>
              </div>
              <div class="textarea_title">
                <span class="textarea_tips">最多增加5行标题</span>
                <a-button @click="riskWordDetnHandle()" size="small"
                  style="font-size: 12px; padding-top: 1px; height: 22px">风险词检测</a-button>
                <!-- <a-button @click="Risk_testRef?.foldOrOpen()" size="small"
                  style="font-size: 12px; padding-top: 1px; height: 22px;">风险词检测</a-button> -->
              </div>
              <!-- {{ activeTextarea + "activeTextarea" }}
              <br />
              {{ activeIndex + "activeIndex" }} -->
            </div>
            <div class="content_main">
  
              <div @click="focusItem(i.id)" class="content_main_item"
                v-for="(i, index) in state[currentDrawerIndex].text_config" :key="i.id">
                <div class="textarea_box" :class="{ active_textarea_box: activeTextarea == i.id }">
                  <span class="textarea_span"> 文本{{ index + 1 }} </span>
                  <textarea v-show="activeTextarea == i.id" maxlength="500" @input="autoResize($event)"
                    @keydown="textareaKeydown($event, index)" v-model="i.text" placeholder="请填写标题内容，按回车增加标题" name=""
                    cols="20" rows="1" :data-textareaId="i.id">
                  </textarea>
                  <div v-show="activeTextarea !== i.id" class="lose_focus">
                    {{ i.text }}
                  </div>

                  <div class="textarea_top_btn" v-show="activeTextarea == i.id">
                  <a-button size="small" type="link" class="subtitle_effect" style="font-size: 13px; line-height: 24px"
                    @click.stop="subtitleSpecialEffects(i)">
                    <template #icon> <copy-outlined /></template>
                    <span>字幕特效{{getEffectsTips(i)}}</span>
                  </a-button>
                  </div>

                  <div class="textarea_right_btn" v-show="activeTextarea == i.id">
                    <a-button size="small" class="btn_tolead" style="font-size: 13px; line-height: 24px"
                      :disabled="state[currentDrawerIndex] >= 5" @click.stop="openCopyLibraryModal">
                      <template #icon> <copy-outlined /></template>
                      <span>文案库导入</span>
                    </a-button>
                    <a-button size="small" class="btn_copy" style="font-size: 13px; line-height: 24px"
                      :disabled="state[currentDrawerIndex].text_config >= 5"
                      @click.stop="addTextareaItem(index, 'copy')">
                      <template #icon> <copy-outlined /></template>
                      <span>创建副本</span></a-button>
                    <span class="textarea_span">{{ i?.text?.length || 0 }}/500</span>
                  </div>
                </div>
              </div>

              <!-- 风险词检测组件 -->
              <!-- <Risk_test ref="Risk_testRef" :disableSubmit="!text_arr.text.trim()" :type="'text_config'"
                :text_arr="text_arr.arr">
              </Risk_test> -->
              <!-- <Risk_test ref="Risk_testRef" :disableSubmit="!text_arr.text.trim()" :type="'text_config'"
                :risk_data="current_editItem?.risk_data_text_config || null" :text_arr="text_arr.arr"
                @testOver="testOver">
              </Risk_test> -->
            </div>
          </div>

          <!-- 视频设置 -->
          <div class="content_item" style="margin-top: 20px">
            <div class="video_settings_title">
              <h2>视频设置</h2>
              <a-button class="btn_prev" @click="applyToAll" style="
                  font-size: 13px;
                  border-radius: 5px;
                  line-height: 20px;
                  padding: 0 16px;
                ">视频设置应用到全部镜头组</a-button>
            </div>
            <!-- 花字组件 -->
            <!-- :groupData="state[currentDrawerIndex].text_config" -->
            <FancyFont ref="fancyFont" @updateState="updateState"
            @updateIsRandom="updateIsRandom"
            @updateConfig_ids="updateConfig_ids"
            @updateFlower_type="updateFlower_type"
            @updateFlower_id="updateFlower_id"
            @clearFlower_config_ids="clearFlower_config_ids"
            :flower_random_config="flower_random_config"
              :state="state[currentDrawerIndex].text_config[activeIndex]" :span_id="`cover_${activeTextarea}`" />
            <div class="control_time">
              <div class="control_time_item">
                <span class="control_time_item_title">开始时间</span>
                <a-input-number @focus="timeInputFocus = true" @blur="timeInputFocus = false"
                  v-model:value="text_startTime" style="width: 185px; padding: 0" allowClear :min="0" :max="4000"
                  :step="0.1" :defaultValue="null" string-mode>
                  <template #addonBefore>
                    <span>第</span>
                  </template>
                  <template #addonAfter>
                    <!-- <span class="clear_btn" >x</span> -->
                    <span>秒</span>
                  </template>
                </a-input-number>
              </div>

              <div class="control_time_item">
                <span class="control_time_item_title">持续时长</span>
                <a-input-number @focus="timeInputFocus = true" @blur="timeInputFocus = false"
                  v-model:value="text_duration" style="width: 130px; padding: 0" allowClear :min="0.1" :max="999999"
                  :step="0.1" :defaultValue="''">
                  <template #addonAfter>
                    <span>秒</span>
                  </template>
                </a-input-number>
                <a-tooltip placement="top" color="#282828" :overlayStyle="{
                  'max-width': 'none',
                  'white-space': 'nowrap',
                }">
                  <template #title>
                    <span style="font-size: 12px">当持续时间大于镜头组时长时，标题展示只会持续到镜头组结束</span>
                  </template>
                  <InfoCircleOutlined class="info_msg"></InfoCircleOutlined>
                </a-tooltip>
              </div>
            </div>
          </div>
          <div id="phoneConCover" :style="{
            opacity: phoneVisible ? 1 : 0,
            transition: 'opacity 0.5s',
            width: 360 + 30 + 'px',
            height: 730 + 47.809 + 'px'
          }" class="phoneConCover_content" v-show="phoneVisible">

            <!-- 手机头部 -->
            <div class="mobile-header">
              <div class="time">{{ dayjs().format("HH:mm") }}</div>
              <div class="wife">
                <cu-icon type="icon-xinhao" style="font-size: 12px"></cu-icon>
                <cu-icon type="icon-wife" style="margin: 0 2px; font-size: 14px"></cu-icon>
                <cu-icon type="icon-electricity-full" style="font-size: 14px"></cu-icon>
              </div>
            </div>
            <!-- 模拟抖音背景 -->
            <div class="bgc_content" :style="{
              'background-image': showImg
                ? `url(${utils.staticPath + 'images/workAi/shotstack/bg_cover.png'
                })`
                : '',
            }"></div>


            <!-- 素材背景图 -->
            <div class="bgc_content" :style="{
              ...parentBgc,
              'z-index': 1,
              left: 0
            }"></div>

            <!-- 底层背景图 -->
            <div class="left_phone_view" :style="{
              ...bgc,
              display: 'flex',
              'justify-content': 'center',
              'align-items': 'center'
            }">
              <!-- <a-spin style="width: 100%; height: 640px" :spinning="loading"> -->
              <DraggableContainer :style="resizableStyle" :referenceLineColor="'white'">
                <!-- v-model:x="item.x" -->
                <!-- style="transform: translateX(-50%)" -->
                <Vue3DraggableResizable style="padding: 0; z-index: 3;" v-show="true" v-for="(item, index) in state[currentDrawerIndex]
                  .text_config" :key="'art_con' + item.id" v-model:x="item.x" v-model:y="item.y" v-model:w="item.width"
                  v-model:h="item.height" v-model:active="item.active" :draggable="true" :resizable="false"
                  :parent="true" @drag-end="dragEndHandle($event, item)">
                  <p :style="coverStyle(item, index, item.id)" class="editor_content"
                    @mousedown="activeTextarea = item.id" :id="'cover_' + item.id" :textContent.prop="item.text"></p>
                </Vue3DraggableResizable>
                <!-- <p :style="{ ...coverStyle(item, index, item.id)}" class="editor_content"
                    @mousedown="activeTextarea = item.id" :id="'cover_' + item.id" :textContent.prop="item.text">
                  </p> -->
              </DraggableContainer>
              <!-- </a-spin> -->
            </div>
            <!-- :initW="item.width" :initH="item.height" -->
            <div class="bottom_View_control">
              <a-button @click="showImg = !showImg">{{ showImg ? "关闭" : "开启" }}抖音视图</a-button>
              <!-- <a-button type="primary">
                <CaretRightOutlined />
                预览效果
              </a-button> -->
            </div>
          </div>
        </div>

        <template #footer>
          <div class="bottom_btn">
            <a-button style="margin-right: 15px" @click="close">取消</a-button>
            <a-button type="primary" @click="submitConfirm">确定</a-button>
          </div>
        </template>
      </a-drawer>
    </transition>
    <!-- 选择素材 -->
    <ChooseMaterial material_type="text" :isClip="true" :multiple="true" :visible="materiallibraryShow"
      @close="closeChooseMaterial($event, 'material_type')" />
    <RiskWordDetection ref="riskWordDetection" />
    <!-- 文案库 -->
    <CopyLibraryModal ref="copyLibraryModal" @importSuccess="closeChooseMaterial" />
      <!-- 字幕特效弹窗 -->
    <SubtitleSpeciallyGoodEffectDialog ref="SubtitleSpeciallyGoodEffectDialogRef"
    @updateTextEffect_config="updateTextEffect_config"
    ></SubtitleSpeciallyGoodEffectDialog>

  </div>
</template>

<style lang="less" scoped>
.content {
  padding-top: 20px;
  position: relative;

  // 手机样式
  .phoneConCover_content {
    // width: 360px;
    // height: 730px;
    background-color: #000;
    display: flex;
    align-items: center;
    justify-content: center;
    position: fixed;
    border-radius: 20px;
    top: 50%;
    left: calc(calc(100% - 50%) / 2);
    transform: translate(-50%, -50%);
    z-index: 9999;

    // 手机头部
    .mobile-header {
      height: 44px;
      width: 100%;
      position: absolute;
      left: 0;
      top: 0;
      border-top-left-radius: 20px;
      border-top-right-radius: 20px;
      border-bottom: 1px solid rgba(255, 255, 255, 0.281);
      background: black;
      display: flex;
      align-items: center;
      justify-content: space-between;
      color: #fff;
      padding: 10px 10px;
      overflow: hidden;
    }

    // 背景图
    .bgc_content {
      position: absolute;
      top: 43.5px;
      left: 0;
      width: 100%;
      // height: 100%;
      height: calc(100% - 88px);
      background-repeat: no-repeat;
      background-size: contain;
      background-size: cover;
      background-size: 100%;

      /* 添加这一行 */
      pointer-events: none;
      z-index: 2;
    }

    .left_phone_view {
      overflow: hidden;
      height: calc(100% - 88px);
      width: 100%;
      display: flex;
      align-items: center;
      justify-content: center;
      border-bottom: 1px solid rgba(255, 255, 255, 0.281);

      .editor_content {
        outline: none;
        // line-height: 1;
        margin-bottom: 0;
        border: none;
        resize: none;
        height: auto;
        display: inline-block;
        pointer-events: none;
        // 换行显示
        white-space: pre-wrap;
        // 不考虑连贯性, 强制换行
        word-break: break-all;
      }
    }

    // 手机下方的控制按钮
    .bottom_View_control {
      position: absolute;
      bottom: -50px;
      left: 50%;
      transform: translate(-50%, 0);
      display: flex;
    }
  }

  .content_item {
    .control_time {
      display: flex;
      flex-direction: column;

      .control_time_item {

        // display: flex;
        // align-items: center;
        // gap: 5px;
        span {
          margin-right: 16px;
          line-height: 30px;
        }

        &:nth-child(1) {
          margin: 20px 0;
        }

        .info_msg {
          margin-left: 12px;
          padding-top: 2px;
        }
      }

      // 清除input 默认样式
      :deep(.ant-input-number-group-wrapper) {
        border-radius: 5px;
        overflow: hidden;
      }

      :deep(.ant-input-number-group-addon) {
        border: none;
        background-color: transparent;
        padding: 0 5px;
        max-width: 30px;

        span {
          margin-right: 0;
        }
      }

      :deep(.ant-input-number-group) {
        background-color: #f4f5f5;
      }

      :deep(.ant-input-number-input) {
        border: none;
        padding-left: 6px;
      }

      :deep(.ant-input-number) {
        border: none;
        background-color: #f4f5f5;

        &:hover {
          border: none;
        }
      }

      :deep(.ant-input-number-focused) {
        box-shadow: none;
      }

      :deep(.ant-input-number-handler) {
        border-right: 1px solid #d9d9d9;
      }
    }

    .content_main {
      background-color: #f6f8fa;
      padding: 30px 12px;
      border-radius: 10px;

      .content_main_item {
        margin-bottom: 10px;

        .textarea_box {
          width: 100%;
          border: 3px solid transparent;
          display: flex;
          // align-items: center;
          padding: 5px 8px;
          position: relative;
          &:hover {
            & .textarea_right_btn .btn_tolead {
              opacity: 1;
            }
            & .textarea_top_btn .subtitle_effect {
              opacity: 1;
            }
          }

          .textarea_span {
            font-size: 12px;
            align-self: flex-start;
            color: #737a87;
            line-height: 26px;
            margin: 0 5px;
          }

          .textarea_right_btn {
            align-self: flex-end;

            .btn_tolead {
              opacity: 0;
              margin-right: 5px;
            }
          }

          .textarea_top_btn{
            position: absolute;
            top: -30px;
            right: 0;
            // left: 0;
            .subtitle_effect{
              opacity: 0;
            }
          }

          textarea {
            flex: 1;
            overflow: hidden;
            line-height: 26px;
            /* 重要：防止用户手动调整大小 */
            resize: none;
            border: none;
            outline: none;
            font-size: 12px;
            color: #1c1f23;
            background-color: transparent;
            padding: 0;
          }

          .lose_focus {
            flex: 1;
            /* 溢出内容隐藏 */
            line-height: 26px;
            overflow: hidden;
            /* 文本溢出显示省略号 */
            text-overflow: ellipsis;
            /* 文本在一行显示 */
            white-space: nowrap;
            font-size: 12px;
            color: #1c1f23;
          }
        }

        .active_textarea_box {
          border-color: var(--ss-primary-color-deprecated-t-20);
          border-radius: 5px;
        }
      }
    }

    .content_item_title {
      display: flex;
      justify-content: space-between;
      align-items: center;
      margin-bottom: 15px;

      .content_item_title_left{
        display: flex;
        align-items: center;
      }

      .textarea_title {
        margin-left: 20px;
        display: flex;
        align-items: center;
        gap: 10px;
      }

      h2 {
        font-size: 13px;
        font-weight: 600;
        color: #1e1c23;
        margin-bottom: 0;
        margin-right: 10px;
      }

      span {
        font-size: 12px;
        color: #737a87;
      }
    }

    .video_settings_title {
      display: flex;
      align-items: center;
      justify-content: space-between;
      margin-bottom: 20px;

      h2 {
        font-size: 13px;
        font-weight: 600;
        color: #1e1c23;
        margin-bottom: 0;
        margin-right: 10px;
      }
    }
  }
}

// 底部按钮
.bottom_btn {
  padding: 8px 24px;
  display: flex;
  justify-content: flex-end;
  background-color: #fff;
}

// 头部样式
.title_box {
  width: 100%;
  padding-bottom: 10px;
  padding-top: 24px;
  position: sticky;
  top: 0;
  z-index: 999;
  background-color: #fff;

  &::after {
    content: "";
    height: 1px;
    width: calc(100% + 48px);
    background-color: #e8e8e8;
    position: absolute;
    bottom: 0;
    left: -24px;
  }

  .title_top {
    display: flex;
    justify-content: space-between;
    color: #0c0d0e;

    // margin-bottom: 10px;
    h1 {
      font-size: 16px;
      font-weight: 600;
      margin-bottom: 4px;
    }

    .close {
      cursor: pointer;
      text-align: center;
      line-height: 29px;
      padding: 0 6px;

      &:hover {
        background-color: #f3f3f4;
      }
    }
  }

  .title_bottom {
    .btn_prev {
      border-radius: 5px;
      padding: 0 16px;
      font-size: 12px;
      height: 28px;
    }
  }
}
</style>
